// ==UserScript==
// @name             Chiikawa 购物优化
// @version          2025-08-11
// @description      优化chiikawa购物体验。1.增加库存展示;2.自动点击用户协议
// @author           alone
// @orginAuthor      Xie Zhihao
// @license          MIT
// @icon             https://www.google.com/s2/favicons?sz=64&domain=chiikawamarket.jp
//
// @match            https://chiikawamarket.jp/*/products/*
// @match            https://chiikawamarket.jp/products/*
// @match            https://chiikawamarket.jp/collections/*/products/*
// @match            https://chiikawamarket.jp/*/collections/*/products/*
// @match            https://chiikawamarket.jp/cart
// @match            https://chiikawamarket.jp/*/cart
// @match            https://nagano-market.jp/products/*
// @match            https://nagano-market.jp/*/products/*
// @match            https://nagano-market.jp/collections/*/products/*
// @match            https://nagano-market.jp/*/collections/*/products/*
// @match            https://nagano-market.jp/cart
// @match            https://nagano-market.jp/*/cart
// @match            https://chiikawamogumogu.shop/products/*
// @match            https://chiikawamogumogu.shop/collections/*/products/*
// @match            https://chiikawamogumogu.shop/cart
//
// @grant            GM_registerMenuCommand
// @grant            GM_unregisterMenuCommand
// @grant            GM_notification
// @grant            GM_info
// @grant            GM_setValue
// @grant            GM_getValue
// @grant            GM_deleteValue
// @grant            GM_openInTab
// @grant            GM_addStyle
// @grant            GM_getResourceText

// @run-at           document-end
// @require          https://gitee.com/zw95cn/my-scripts/raw/master/js/libs/jquery/3.5.1/jquery.min.js
// @require          https://gitee.com/zw95cn/my-scripts/raw/master/js/libs/pako/2.0.3/pako.min.js
// @require          https://gitee.com/zw95cn/my-scripts/raw/master/js/libs/ElementGetter.js
// @require          https://gitee.com/zw95cn/my-scripts/raw/master/js/libs/sweetalert2.js
// @require          https://gitee.com/zw95cn/my-scripts/raw/master/js/libs/myLib.js
// @resource         customCSS https://gitee.com/zw95cn/my-scripts/raw/master/js/libs/css/myCss.css

// @homepageURL      https://gitee.com/zw95cn/my-scripts/blob/master/js/youhou
// @updateURL        https://gitee.com/zw95cn/my-scripts/raw/master/js/youhou/ChiikawaMarketStorageChecker.user.js
// ==/UserScript==

var updateDate = GM_info.script.version

const configIdList = [
  { group: '默认', id: 'addAvalAmountTip', title: '商品详情页、购物车添加库存展示', name: '添加库存展示' },
  { group: '默认', id: 'autoCheckAgreementBox', title: '自动点击用户协议', name: '自动点击用户协议' },
  { group: '默认', id: 'addAddToCartDontLink', title: '添加加购不跳转按钮', name: '添加加购不跳转按钮' },
];

const scriptInfo = GM_info.script,
  locHost = location.host,
  locHref = location.href,
  locHash = location.hash,
  locPath = location.pathname

// 配置对象
let t = {
  showNotice(msg) {
    GM_notification({
      text: msg,
      title: scriptInfo.name,
      image: scriptInfo.icon,
      highlight: false,
      silent: false,
      timeout: 1500,
    })
  },

  clog() {
    for (let m of arguments) {
      if (void 0 !== m) console.log(m)
    }
    console.groupEnd()
  },

  get(name, def) {
    return GM_getValue(name, def)
  },

  set(name, value) {
    GM_setValue(name, value)
  },

  setIfAbsent(name, value) {
    if (GM_getValue(name, null) == null) GM_setValue(name, value)
  },

  delete(name) {
    GM_deleteValue(name)
  },

  registerMenu(title, func) {
    return GM_registerMenuCommand(title, func)
  },

  unregisterMenu(menuID) {
    GM_unregisterMenuCommand(menuID)
  },

  open(url, options = { active: true, insert: true, setParent: true }) {
    GM_openInTab(url, options)
  },

  http(link, s = false) {
    return link.startsWith('http') ? link : (s ? 'https://' : 'http://') + link
  },

  title(a, mark = '') {
    if (a.title) a.title += '\n' + mark + decodeURIComponent(a.href)
    else a.title = mark + decodeURIComponent(a.href)
  },

  hashcode(l = location) {
    return l.hash.slice(1)
  },

  search(l = location, p = 'password') {
    let args = l.search.slice(1).split('&')
    for (let a of args) {
      if (a.includes(p + '=')) return a.replace(p + '=', '')
    }
    return ''
  },

  clean(src, str) {
    for (let s of str) {
      src = src.replace(s, '')
    }
    return src
  },

  loop(func, times) {
    let tid = setInterval(() => {
      if (times <= 0) clearInterval(tid)
      func()
      this.clog(times)
      times--
    }, 100)
  },

  confirm(title, yes, no = () => {}, deny = false) {
    let option = {
      toast: true,
      showCancelButton: true,
      position: 'center',
      title,
      confirmButtonText: '是',
      cancelButtonText: '否',
      showDenyButton: deny,
      denyButtonText: '取消',
      customClass: {
        popup: 'lh-popup',
        content: 'lh-content',
        closeButton: 'lh-close',
      },
    }
    return Swal.fire(option).then((res) => {
      if (res.isConfirmed) yes()
      else if (res.isDismissed) no()
      else if (res.isDenied) deny()
    })
  },

  rand(min, max) {
    if (arguments.length == 1) (max = min), (min = 0)
    let random = Math.random(),
      randInt = Math.floor(random * (max + 1 - min)) + min
    return randInt
  },
}
// 注册配置弹窗
function registerMenu() {
  // 如果没设置值 默认为true
  configIdList.forEach((v) => {
    t.setIfAbsent(v.id, true)
  })

  function generateHtml(config) {
    let html = `<ul class="lh-menu">`

    // 用于跟踪当前分组
    let currentGroup = null

    config.forEach((item) => {
      if (item.group !== currentGroup) {
        // 如果分组变化，添加新的分组标题
        html += `<li class="lh-item lh-item-group">
                   <span>${item.group}</span>
                 </li>`
        currentGroup = item.group
      }
      // 添加功能项
      html += `<li class="lh-item">
                 <label title="${item.title}">
                   <input type="checkbox" id="${item.id}"/>
                   <span class="checkBoxText">${item.name}</span>
                 </label>
               </li>`
    })

    html += `</ul>`
    return html
  }

  function showSettings() {
    let html = generateHtml(configIdList)

    Swal.fire({
      title: '配置',
      html,
      footer: `<div class="lh-footer">
							   <span>${formatDateVersionToDesc(updateDate)}更新</span>
							 </div>`,
      showCloseButton: true,
      showConfirmButton: true,
      showDenyButton: true,
      confirmButtonText: '保存',
      denyButtonText: '恢复默认',
      customClass: {
        popup: 'lh-popup',
        content: 'lh-content',
        closeButton: 'lh-close',
      },
      didOpen: () => {
        configIdList.forEach((v) => {
          $(`#${v.id}`).prop('checked', t.get(v.id) == true, false)
        })
      },
    }).then((result) => {
      // 根据设置展示控件选中状态

      if (result.isConfirmed) {
        // 保存配置并刷新
        configIdList.forEach((v) => {
          t.set(v.id, $(`#${v.id}`).prop('checked') || false)
        })
        createAlert('已保存，稍后刷新', 'success')
        setTimeout(() => {
          window.location.reload()
        }, 3000)
      } else if (result.isDenied) {
        // 重置
        configIdList.forEach((v) => {
          t.delete(v.id)
        })
        createAlert('已重置，稍后刷新', 'success')
        setTimeout(() => {
          window.location.reload()
        }, 3000)
      }
    })
  }
  GM_addStyle(
    deGzip(
      `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`
    )
  )
  t.registerMenu('配置', showSettings)
}

// 运行启动的功能项
function Work() {
  configIdList.forEach((v) => {
    if (t.get(v.id) == true) {
      var func = eval(v.id)
      func()
    }
  })
}

// 个性函数部分  ================================================================================
const MAX_QUANTITY = 1000000;

// 获取是否有库存
const isAval = async () => {
  const pd = getIdAndProductId();
  const res = await fetch(`/products/${pd.dataSku}.js`, {
    headers: {
      accept: "*/*",
    },
  });
  const data = await res.json();
  return data.variants[0].available || false;
};

// 获取购物车
const getCart = async () => {
  const res = await fetch("/cart.js", {
    headers: {
      accept: "*/*",
    },
  });
  const data = await res.json();
  return data?.items;
};
const getIdAndProductId = () => {
  // 获取商品ID
  const productId = document.querySelector('input[name="product-id"]')?.getAttribute("value");
  let id = document.getElementsByClassName("product-form--variant-select")?.[0]?.children?.[0]?.getAttribute("value");
  let dataSku = document.getElementsByClassName("product-form--variant-select")?.[0]?.children?.[0]?.getAttribute("data-sku");
  if (!id) {
    // Chiikawa Mogumogu Honpo 在线商店.
    id = document.getElementsByClassName("product__pickup-availabilities")?.[0]?.getAttribute("data-variant-id");
  }
  if (!productId || !id) {
    return null;
  }
  return {id,productId,dataSku}
}

// 添加商品到购物车
const addItem = async (id, productId, quantity) => {
  const res = await fetch("/cart/add.js", {
    headers: {
      accept: "application/javascript",
      "content-type": "multipart/form-data; boundary=----WebKitFormBoundary788zedotmtSec399",
      "x-requested-with": "XMLHttpRequest",
    },
    method: "POST",
    body: `------WebKitFormBoundary788zedotmtSec399\r\nContent-Disposition: form-data; name="form_type"\r\n\r\nproduct\r\n------WebKitFormBoundary788zedotmtSec399\r\nContent-Disposition: form-data; name="utf8"\r\n\r\n✓\r\n------WebKitFormBoundary788zedotmtSec399\r\nContent-Disposition: form-data; name="id"\r\n\r\n${id}\r\n------WebKitFormBoundary788zedotmtSec399\r\nContent-Disposition: form-data; name="quantity"\r\n\r\n${quantity}\r\n------WebKitFormBoundary788zedotmtSec399\r\nContent-Disposition: form-data; name="product-id"\r\n\r\n${productId}\r\n------WebKitFormBoundary788zedotmtSec399\r\nContent-Disposition: form-data; name="section-id"\r\n\r\ntemplate--18391309091057__main\r\n------WebKitFormBoundary788zedotmtSec399--\r\n`,
  });
  return res.status;
};

// 获取购物车指定商品的数量
const getItem = async (id) => {
  const items = await getCart();
  const item = items?.find((e) => e?.id == id);
  if (item) {
    return item.quantity;
  }
  return 0;
};
// 购物车删除物品
const removeItem = async (id) => {
  const items = await getCart();
  const index = items?.findIndex((e) => e?.id == id);
  if (index >= 0) {
    await fetch("/cart/change.js", {
      headers: {
        accept: "*/*",
        "content-type": "application/json",
      },
      method: "POST",
      body: `{"line":${index + 1},"quantity":0}`,
    });
    return items[index]?.quantity ?? 0;
  }
  return 0;
};

// 获取指定商品库存
const checkGetAvalAmount = async (id, productId, currentQuantity, fn) => {
  await removeItem(id);

  // 添加足够多到购物车，只会加成功剩余库存的数量
  await addItem(id, productId, MAX_QUANTITY);

  // 获取加入成功的库存数
  const quantity = await getItem(id);
  fn(`${quantity}`);

  // 清除购物车
  await removeItem(id);

  // 如果自己手动加过购物车，则恢复之前的数量
  if (currentQuantity) {
    try {
      await addItem(id, productId, currentQuantity);
    } catch {}
  }
};

const checkCart = async () => {
  // 检查当前购物车内商品库存
  let currentItems;
  try {
    currentItems = await getCart();
  } catch {}
  if (!currentItems) {
    return;
  }

  // https://chiikawamarket.jp/cart ，电脑端和手机端元素同时出现在网页，所以有两份
  const items = document.querySelectorAll(`.cart--root .cart--item`);
  for (let i = 0; i < items.length / 2; i++) {
    // Make sure the label is valid.
    const label1 = items[i].querySelector(".avlAmount");
    const label2 = items[i + items.length / 2].querySelector(".avlAmount");
    if (!label1 || !label2) {
      continue;
    }
    const svgIcons = document.querySelectorAll(".cart--root .cart--header .refreshAmount svg");
    for (var svg of svgIcons){
      svg.classList.add('rotate')
    }
    // Get product ID and ID for storage checking.
    const id = items[i].getAttribute("data-variant-id");
    if (!id) {
      continue;
    }
    const productId = currentItems.find((e) => e?.id == id)?.product_id;
    if (!productId) {
      continue;
    }

    // Get current quantity.
    let currentQuantity = currentItems.find((e) => e?.id == id)?.quantity ?? 0;

    // Check storage.
    label1.textContent = `剩余库存数： ...`;
    label2.textContent = ` / 剩余库存数： ...`;
    await checkGetAvalAmount(id, productId, currentQuantity, (t) => {
      label1.textContent = `剩余库存数： ${t}`;
      label2.textContent = ` / 剩余库存数： ${t}`;
      for (var svg of svgIcons){
        svg.classList.remove('rotate')
      }
    });
  }

  // https://chiikawamogumogu.shop/cart 电脑端和手机端元素共用，所以有一份
  const items2 = document.querySelectorAll(`#main-cart-items .cart-items  tr.cart-item`);
  for (let i = 0; i < items2.length ; i++) {
    // Make sure the label is valid.
    const label1 = items2[i].querySelector(".avlAmount");
    if (!label1 ) {
      continue;
    }
    const svgIcons = document.querySelectorAll(".cm-cart-container .cm-container .title-wrapper .refreshAmount svg");
    for (var svg of svgIcons){
      svg.classList.add('rotate')
    }
    const id = items2[i].querySelector('.cart-item__quantity .quantity__input').getAttribute("data-quantity-variant-id");
    if (!id) {
      debugger
      createAlert(`第${i+1}个商品未找到商品ID`,'error')
      continue;
    }
    const productId = currentItems.find((e) => e?.id == id)?.product_id;
    if (!productId) {
      createAlert(`第${i+1}个商品未找到商品productId`,'error')
      continue;
    }

    // Get current quantity.
    let currentQuantity = currentItems.find((e) => e?.id == id)?.quantity ?? 0;

    // Check storage.
    label1.textContent = `剩余库存数： ...`;
    await checkGetAvalAmount(id, productId, currentQuantity, (t) => {
      label1.textContent = `剩余库存数： ${t}`;
      for (var svg of svgIcons){
        svg.classList.remove('rotate')
      }
    });
  }

};
const checkProduct = async () => {
  // 确保标签有效
  let label = document.querySelector(".product-page--avl-amount > .avlAmount");
  if (!label) {
    createAlert('找不到库存标签，请调整脚本','error')
    return;
  }

  const svgIcon = document.querySelector(".product-page--avl-amount .refreshAmount svg");
  svgIcon.classList.add('rotate')

  // 获取商品ID
  const productId = document.querySelector('input[name="product-id"]')?.getAttribute("value");
  let id = document.getElementsByClassName("product-form--variant-select")?.[0]?.children?.[0]?.getAttribute("value");
  if (!id) {
    // Chiikawa Mogumogu Honpo 在线商店.
    id = document.getElementsByClassName("product__pickup-availabilities")?.[0]?.getAttribute("data-variant-id");
  }
  if (!productId || !id) {
    return;
  }

  // 获取购物车已有库存
  let currentQuantity = 0;
  try {
    currentQuantity = await getItem(id);
  } catch {}

  label.textContent = `...`;
  // 检查库存
  await checkGetAvalAmount(id, productId, currentQuantity, (t) => {
    label.textContent = `${t}`;
    svgIcon.classList.remove('rotate')
  });
};

function addAvalAmountTip(){

  GM_addStyle(`
    @keyframes rotate {
        from {
            transform: rotate(0deg);
        }
        to {
            transform: rotate(360deg);
        }
    }

    .rotate {
        animation: rotate 1s linear infinite;
    }
    .product-page--avl-amount {
      font-family: system-ui;
      color: red;
      font-size: 20px;
      display: flex;
    }
    #refreshAvalAmoutIcon {
      font-family: system-ui;
      width: 16px;
      fill: #85b4fa;
      cursor: pointer;
    }
    .avlAmount {
      font-family: system-ui;
      color: red;
      font-size: 20px;
    }



    .cm-cart-container .cm-container .title-wrapper{
      margin-bottom: 3rem;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  `)

  if (document.location.pathname.endsWith("/cart")) {
    // 购物车

    // 在每个商品的可购数量下面加库存。电脑端/手机端标题通用
    // https://chiikawamarket.jp/cart
    elmGetter.each('.cart--root .cart--header .cart--title', document, (cartTitleDiv) => {
      var avlAmountBth = createDivByHtml('<span title="点击刷新库存" class="refreshAmount"><svg  xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" style="width: 16px;fill: #ff0000;cursor: pointer;"><path d="M105.1 202.6c7.7-21.8 20.2-42.3 37.8-59.8c62.5-62.5 163.8-62.5 226.3 0L386.3 160 352 160c-17.7 0-32 14.3-32 32s14.3 32 32 32l111.5 0c0 0 0 0 0 0l.4 0c17.7 0 32-14.3 32-32l0-112c0-17.7-14.3-32-32-32s-32 14.3-32 32l0 35.2L414.4 97.6c-87.5-87.5-229.3-87.5-316.8 0C73.2 122 55.6 150.7 44.8 181.4c-5.9 16.7 2.9 34.9 19.5 40.8s34.9-2.9 40.8-19.5zM39 289.3c-5 1.5-9.8 4.2-13.7 8.2c-4 4-6.7 8.8-8.1 14c-.3 1.2-.6 2.5-.8 3.8c-.3 1.7-.4 3.4-.4 5.1L16 432c0 17.7 14.3 32 32 32s32-14.3 32-32l0-35.1 17.6 17.5c0 0 0 0 0 0c87.5 87.4 229.3 87.4 316.7 0c24.4-24.4 42.1-53.1 52.9-83.8c5.9-16.7-2.9-34.9-19.5-40.8s-34.9 2.9-40.8 19.5c-7.7 21.8-20.2 42.3-37.8 59.8c-62.5 62.5-163.8 62.5-226.3 0l-.1-.1L125.6 352l34.4 0c17.7 0 32-14.3 32-32s-14.3-32-32-32L48.4 288c-1.6 0-3.2 .1-4.8 .3s-3.1 .5-4.6 1z"></path></svg></span>')
      avlAmountBth.addEventListener('click',() => {
        checkCart();
      })
      cartTitleDiv.appendChild(avlAmountBth);
      setTimeout(()=>{
        if(window.getComputedStyle(avlAmountBth.parentNode.parentNode.parentNode).display !== 'none'){
          avlAmountBth.click();
          createAlert('刷新库存中','info')
        }
      },500);
    });
    // 电脑端购物车商品列表
    elmGetter.each('.cart--root[data-view="desktop"] .cart--item > .cart--item--image > div', document, (cartCanBuyAmountDesc) => {
      var avlAmountSpan = createDivByHtml('<div class="avlAmount" > 剩余库存数： *</div>')
      cartCanBuyAmountDesc.appendChild(avlAmountSpan);
    });

    // 手机端购物车商品列表
    elmGetter.each('.cart--root[data-view="mobile"] .cart--item > .cart--item--title > div', document, (cartCanBuyAmountDesc) => {
      var avlAmountSpan = createDivByHtml('<span class="avlAmount" > / 剩余库存数： *</span>')
      cartCanBuyAmountDesc.appendChild(avlAmountSpan);
    });

    // https://chiikawamogumogu.shop/cart
    elmGetter.each('.cm-cart-container .cm-container .title-wrapper', document, (cartTitleDiv) => {
      var avlAmountBth = createDivByHtml('<span title="点击刷新库存" class="refreshAmount"><svg  xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" style="width: 16px;fill: #ff0000;cursor: pointer;"><path d="M105.1 202.6c7.7-21.8 20.2-42.3 37.8-59.8c62.5-62.5 163.8-62.5 226.3 0L386.3 160 352 160c-17.7 0-32 14.3-32 32s14.3 32 32 32l111.5 0c0 0 0 0 0 0l.4 0c17.7 0 32-14.3 32-32l0-112c0-17.7-14.3-32-32-32s-32 14.3-32 32l0 35.2L414.4 97.6c-87.5-87.5-229.3-87.5-316.8 0C73.2 122 55.6 150.7 44.8 181.4c-5.9 16.7 2.9 34.9 19.5 40.8s34.9-2.9 40.8-19.5zM39 289.3c-5 1.5-9.8 4.2-13.7 8.2c-4 4-6.7 8.8-8.1 14c-.3 1.2-.6 2.5-.8 3.8c-.3 1.7-.4 3.4-.4 5.1L16 432c0 17.7 14.3 32 32 32s32-14.3 32-32l0-35.1 17.6 17.5c0 0 0 0 0 0c87.5 87.4 229.3 87.4 316.7 0c24.4-24.4 42.1-53.1 52.9-83.8c5.9-16.7-2.9-34.9-19.5-40.8s-34.9 2.9-40.8 19.5c-7.7 21.8-20.2 42.3-37.8 59.8c-62.5 62.5-163.8 62.5-226.3 0l-.1-.1L125.6 352l34.4 0c17.7 0 32-14.3 32-32s-14.3-32-32-32L48.4 288c-1.6 0-3.2 .1-4.8 .3s-3.1 .5-4.6 1z"></path></svg></span>')
      avlAmountBth.addEventListener('click',() => {
        checkCart();
      })
      cartTitleDiv.appendChild(avlAmountBth);
      setTimeout(()=>{
          checkCart();
          createAlert('刷新库存中','info')
      },500);
    });

    // 购物车商品列表
    elmGetter.each('#main-cart-items .cart-items  tr.cart-item > .cart-item__details', document, (cartCanBuyAmountDesc) => {
      var avlAmountSpan = createDivByHtml('<span class="avlAmount" > 剩余库存数： *</span>')
      cartCanBuyAmountDesc.appendChild(avlAmountSpan);
    });

  } else {
    // 商品详情

    elmGetter.each('.product-page--header', document, (productDiv) => {
      // 商品标题模块
      var avlAmountDiv = createDivByHtml('<div class="product-page--avl-amount">库存<span title="点击刷新库存" class="refreshAmount"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" style="width: 16px;fill: #ff0000;cursor: pointer;"><path d="M105.1 202.6c7.7-21.8 20.2-42.3 37.8-59.8c62.5-62.5 163.8-62.5 226.3 0L386.3 160 352 160c-17.7 0-32 14.3-32 32s14.3 32 32 32l111.5 0c0 0 0 0 0 0l.4 0c17.7 0 32-14.3 32-32l0-112c0-17.7-14.3-32-32-32s-32 14.3-32 32l0 35.2L414.4 97.6c-87.5-87.5-229.3-87.5-316.8 0C73.2 122 55.6 150.7 44.8 181.4c-5.9 16.7 2.9 34.9 19.5 40.8s34.9-2.9 40.8-19.5zM39 289.3c-5 1.5-9.8 4.2-13.7 8.2c-4 4-6.7 8.8-8.1 14c-.3 1.2-.6 2.5-.8 3.8c-.3 1.7-.4 3.4-.4 5.1L16 432c0 17.7 14.3 32 32 32s32-14.3 32-32l0-35.1 17.6 17.5c0 0 0 0 0 0c87.5 87.4 229.3 87.4 316.7 0c24.4-24.4 42.1-53.1 52.9-83.8c5.9-16.7-2.9-34.9-19.5-40.8s-34.9 2.9-40.8 19.5c-7.7 21.8-20.2 42.3-37.8 59.8c-62.5 62.5-163.8 62.5-226.3 0l-.1-.1L125.6 352l34.4 0c17.7 0 32-14.3 32-32s-14.3-32-32-32L48.4 288c-1.6 0-3.2 .1-4.8 .3s-3.1 .5-4.6 1z"></path></svg></span>： <span class="avlAmount">*</span></div>')
      avlAmountDiv.querySelector('.refreshAmount').addEventListener('click',() => {
        checkProduct();
      })
      productDiv.appendChild(avlAmountDiv);
      setTimeout(()=>{
        avlAmountDiv.querySelector('.refreshAmount').click();
      },500);
    });

    // https://chiikawamogumogu.shop/products/*
    elmGetter.each('product-info.product__info-container', document, (productDiv) => {
      // 商品标题模块
      var avlAmountDiv = createDivByHtml('<div class="product-page--avl-amount">库存<span title="点击刷新库存" class="refreshAmount"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" style="width: 16px;fill: #ff0000;cursor: pointer;"><path d="M105.1 202.6c7.7-21.8 20.2-42.3 37.8-59.8c62.5-62.5 163.8-62.5 226.3 0L386.3 160 352 160c-17.7 0-32 14.3-32 32s14.3 32 32 32l111.5 0c0 0 0 0 0 0l.4 0c17.7 0 32-14.3 32-32l0-112c0-17.7-14.3-32-32-32s-32 14.3-32 32l0 35.2L414.4 97.6c-87.5-87.5-229.3-87.5-316.8 0C73.2 122 55.6 150.7 44.8 181.4c-5.9 16.7 2.9 34.9 19.5 40.8s34.9-2.9 40.8-19.5zM39 289.3c-5 1.5-9.8 4.2-13.7 8.2c-4 4-6.7 8.8-8.1 14c-.3 1.2-.6 2.5-.8 3.8c-.3 1.7-.4 3.4-.4 5.1L16 432c0 17.7 14.3 32 32 32s32-14.3 32-32l0-35.1 17.6 17.5c0 0 0 0 0 0c87.5 87.4 229.3 87.4 316.7 0c24.4-24.4 42.1-53.1 52.9-83.8c5.9-16.7-2.9-34.9-19.5-40.8s-34.9 2.9-40.8 19.5c-7.7 21.8-20.2 42.3-37.8 59.8c-62.5 62.5-163.8 62.5-226.3 0l-.1-.1L125.6 352l34.4 0c17.7 0 32-14.3 32-32s-14.3-32-32-32L48.4 288c-1.6 0-3.2 .1-4.8 .3s-3.1 .5-4.6 1z"></path></svg></span>： <span class="avlAmount">*</span></div>')
      avlAmountDiv.querySelector('.refreshAmount').addEventListener('click',() => {
        checkProduct();
      })
      productDiv.insertBefore(avlAmountDiv,productDiv.querySelector('.product__sku'));
      // productDiv.appendChild(avlAmountDiv);
      setTimeout(()=>{
        avlAmountDiv.querySelector('.refreshAmount').click();
      },500);
    });
  }

}

function autoCheckAgreementBox(){
  // 购物详情页
  elmGetter.each('#productAgree', document, (productAgree) => {
    productAgree.click();
    productAgree.checked = true;
    var addCartBtn = document.querySelector("div.product-form--button-container > button");
    addCartBtn.removeAttribute('disabled');
  });

  // 购物车
  elmGetter.get('#termsCheck').then(termsCheck => {
    termsCheck.click();
    termsCheck.checked = true;
    var buyBtn = document.querySelector("div.cart_navi > div.cart_button > div > button");
    buyBtn.removeAttribute('disabled');
  });

}

function addAddToCartDontLink(){
  GM_addStyle(`
    .product-form--add-dont-link {
      width: 100%;
      background-color: #d00;
      font-family: system-ui;
      font-weight: bold;
      font-size: 1rem;
      color: white;
    }
    .product-form--add-dont-link:hover {
      background-color: #dd000099 !important;
    }
    .product-form--text{
      font-family: system-ui !important;
    }
    .product-form--add-to-cart:hover{
      background-color: #2f9ae099 !important;
    }
  `)

  elmGetter.each('.product-form--button-container', document, async (productAddCartContainer) => {

    const isPdAval = await isAval();
    if(isPdAval){
      const addCartDontLinkDiv = createDivByHtml(`<button class="product-form--add-dont-link" style="visibility: visible;"> <span>添加到购物车(不跳转)</span> </button>`);
      // 获取商品ID
      const {id, productId} = getIdAndProductId();

      addCartDontLinkDiv.addEventListener('click',() => {
        try {
          addItem(id, productId, 1);
        } catch {}
        finally{
          createAlert('添加成功','success')
        }
      });
      productAddCartContainer.parentNode.parentNode.insertBefore(addCartDontLinkDiv,productAddCartContainer.parentNode);

    }
      // 将添加购物车挪到前面
      productAddCartContainer.parentNode.insertBefore(productAddCartContainer,productAddCartContainer.parentNode.firstChild);
  });
}

;(function () {
  'use strict'
  registerMenu()
  Work()
})()
